<?php

declare(strict_types=1);

namespace catchAdmin\monitor\command;

use Carbon\Carbon;
use catchAdmin\product\model\Product;
use catchAdmin\supply\model\SubOrders;
use catchAdmin\warehouse\model\ReplenishmentWarning;
use catchAdmin\warehouse\model\WarehouseOrderProducts;
use catchAdmin\warehouse\model\Warehouses;
use catchAdmin\warehouse\model\WarehouseStock;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use catcher\Code;
use think\facade\Db;

class ReplenishmentWarningCommand extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('catch:replenishmentWarning')
            ->setDescription('库存预警补货');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('ReplenishmentWarning Error Line:' . $e->getLine());
            Log::error('ReplenishmentWarning Error Code:' . $e->getCode());
            Log::error('ReplenishmentWarning Error Message:' . $e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }


    /**
     * 执行 command
     *
     * @time 2021年05月10日
     * @return void
     */
    protected function executeCommand()
    {
        Log::info('catch:replenishmentWarning库存预警补货:' . date('Y-m-d H:i:s'));
        $year   = date('Y');
        $months = '';
        for ($i = 1; $i <= 3; $i++) {
            $months .= '`' . date('M', strtotime("+{$i} month"))  . '`+';
        }

        $months   = strtolower(substr($months, 0, -1));
        $query  = Product::field('product.id, code, name_ch, name_en')
            ->where(['is_disable' => '1', 'packing_method' => '1', 'status' => '1', 'deleted_at' => 0]);



        // $warehouseId = '';
        // if (isset($params['warehouse']) && $params['warehouse']) {
        //     $warehouseId = Warehouses::where('name', $params['warehouse'])->value('id');
        //     $query->leftJoin('warehouse_stock', 'warehouse_stock.goods_code= product.code')
        //           ->where('warehouse_stock.entity_warehouse_id', $warehouseId);
        // }

        $products = $query->select();
        $rpmodel = new ReplenishmentWarning();
        foreach ($products as $product) {
            $product = $product->toArray();
            //计算即时库存
            $stockQuery = WarehouseStock::where('goods_code', $product['code']);
            // if ($warehouseId){
            //     $stockQuery->where('entity_warehouse_id', $warehouseId);
            // }
            $product['stock'] = $stockQuery->sum('number');

            //计算在途库存
            $product['trans_stock'] = WarehouseOrderProducts::alias('wop')
                ->leftJoin('warehouse_orders wo', 'wo.id = wop.warehouse_order_id')
                ->where([
                    'wop.goods_code' => $product['code'],
                    'wo.warehousing_status' => 0,
                    'wo.deleted_at' => 0,
                ])
                ->sum('number') ?? 0;

            //获取后三个月预计销量之和
            $sql = "select sum($months) as total from sales_forecast_products sfp, sales_forecast sf where sf.id = sfp.sales_forecast_id and sf.year = {$year} and goods_code = '{$product['code']}'";

            $salse = Db::query($sql);

            $product['salse'] = $salse[0]['total'] > 0 ? $salse[0]['total'] : 0;
            $product['check_date'] = date('Y-m-d');

            if ((int)($product['stock'] + $product['trans_stock']) < $product['salse']) {
                $rpmodel->createBy($product);
            }
        }
    }
}
